package utils;

import book.PairOfUserIDAndBookID;
import com.bit.utils.FileUtils;
import book.Book;
import java.io.IOException;

//用于存储每个用户借阅的信息
public class AnalyzingBorrowedBook {
    public void storeUserBook(PairOfUserIDAndBookID[] pairOfUserIDAndBookID,String filename) throws IOException {
        //先遍历出pairOfUserIDAndBookID数组中真实到底有多少个借书对象
        int bookBorrowedNum = 0;
        for (int i = 0; i < pairOfUserIDAndBookID.length; i++) {
            if(pairOfUserIDAndBookID[i] != null) {
                bookBorrowedNum++;
            }
        }
        //for循环后得到总共有多少借书对象
        //再将信息以字符串的形式存储
        StringBuilder stringBooks = new StringBuilder();
        for (int i = 0; i < bookBorrowedNum; i++) {
            if(pairOfUserIDAndBookID[i]!=null) {
                stringBooks.append(pairOfUserIDAndBookID[i].tostring());
                if(i != bookBorrowedNum-1) {
                    stringBooks.append("\n");
                }
            }
        }
        //将stringBooks字符串写入文件中
        FileUtils.writeFile(stringBooks.toString(),filename);
    }

    public PairOfUserIDAndBookID[] loadUserBook(String filename) throws IOException {
        //1、从文件中读取数据
        String content = FileUtils.readFile(filename);

        //判断借阅图书是否为空
        if(content == null || content.isEmpty()) {
            //System.out.println("文件中没有人借阅书籍！");
            return null;
        }

        //2、解析出PairOfUserIDAndBookID对象，以\n分割数据，存储到数组里面

        String[] bookBorrowedStr = content.split("\n");

        //3、把对应字符串“组装”成借阅书籍对象

        PairOfUserIDAndBookID[] bookList = new PairOfUserIDAndBookID[bookBorrowedStr.length];
        for (int i = 0; i < bookList.length; i++) {
            bookList[i] = parseBookString(bookBorrowedStr[i]);
        }
        return bookList;
    }

    private PairOfUserIDAndBookID parseBookString(String string) {
        //分割得到借阅的每个信息
        String[] pairs = string.split(",");
        //将每个属性进行赋值
        int userID = Integer.parseInt(pairs[0]);
        int bookID = Integer.parseInt(pairs[1]);
        return new PairOfUserIDAndBookID(userID,bookID);
    }
}
